/**
 * 单例模式
 * 此类的子类只能被实例化一次
 */
export class Singleton<T> {
  private static instances: Map<string, any> = new Map();

  protected constructor() {
    // 防止直接实例化
    if ((this.constructor as any)._hasInstance) {
      throw new Error("单例不能被 构造方法实例化");
    }
    (this.constructor as any)._hasInstance = true;
  }

  public static getInstance<T>(): T {
    const className = this.name;

    if (!Singleton.instances.has(className)) {
      Singleton.instances.set(className, new this());
    }

    return Singleton.instances.get(className) as T;
  }
}
